/**
 * Created by 余保林 on 2017/8/8.
 */
import {Message} from 'iview'
import axios from 'axios'

const CODE = {
  success: 0,
  fail: 2,
  error: 3
}

function ajax ({method, url, success, params = {}, data = {}, fail = null}) {
  axios({
    url,
    method,
    params,
    data,
    timeout: 2000
  }).then((res) => {
    let resData = res.data
    switch (resData.code) {
      case CODE.success:
        success(resData.data)
        break
      case CODE.fail:
        if (fail) {
          fail(resData.msg)
        } else {
          Message.warning(resData.msg)
        }
        break
      case CODE.error:
        Message.error(resData.msg)
    }
  }).catch((err) => {
    Message.error(err.message)
    console.log(err)
  })
}

export default {
  get: ({url, params = {}, success, fail = null}) => {
    ajax({method: 'get', url, success, params, fail})
  },
  post: ({url, data = {}, success, fail = null}) => {
    ajax({method: 'post', url, success, data, fail})
  }
}
